package com.springboot.demo.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author JuoChiu
 * 聚合：证件图片识别封装
 * */
public class JuHeUtils {
    private Logger log = LoggerFactory.getLogger(JuHeUtils.class);
	private static final String type = "6";
	
	// 请求代码
	/*public static String get() throws IOException {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = null;
        try {
            HttpGet httpGet = new HttpGet(Constants.JUHE_API_URL);
            // 执行网络请求
            response = httpClient.execute(httpGet);
            // 获取请求实体
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                // ConverStreamToString是下面写的一个方法是把网络请求的字节流转换为utf8的字符串
                result = ConvertStreamToString(resEntity.getContent(), "UTF-8");
            }
            EntityUtils.consume(resEntity);
        } catch (Exception e) {
        } finally {
            // 关闭请求
            response.close();
            httpClient.close();
        }
        // 得到的是JSON类型的数据需要第三方解析JSON的jar包来解析
        return result;
    }*/
		
    /**
     * @author JuoChiu
     * 此方法是POST请求上传的参数中包含本地图片信息File类型
     * @param {type：证件类型，默认为6；file 图片信息流}
     * @return
     * @throws Exception
     */
    public static String juhePost(String url) throws Exception {
    	
    	CloseableHttpClient httpClient = HttpClients.createDefault();

    	HttpGet httpget = new HttpGet(url);

    	CloseableHttpResponse response2 = httpClient.execute(httpget);

    	InputStream content = response2.getEntity().getContent();

    	InputStreamBody body = new InputStreamBody(content, "filename");
    	
        CloseableHttpResponse response = null;
        String result = null;
        // HttpClient请求的相关设置，可以不用配置，用默认的参数，这里设置连接和超时时长(毫秒)
        RequestConfig config = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build();
        try {
            HttpPost httppost = new HttpPost(Constants.JUHE_API_IMAGE_URL);
            // FileBody封装File类型的参数
            // FileBody bin = new FileBody(file);
			// StringBody封装String类型的参数
            StringBody keyBody = new StringBody(Constants.JUHE_API_KEY, ContentType.TEXT_PLAIN);
            StringBody typeBody = new StringBody(type, ContentType.TEXT_PLAIN);
            // addPart将参数传入，并指定参数名称
            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("pic", body).addPart("key", keyBody).addPart("cardType", typeBody).build();
            httppost.setEntity(reqEntity);
            httppost.setConfig(config);
            // 执行网络请求并返回结果
            response = httpClient.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
            	// ConverStreamToString是下面写的一个方法是把网络请求的字节流转换为utf8的字符串
                result = ConvertStreamToString(resEntity.getContent(), "UTF-8");
            }
            EntityUtils.consume(resEntity);
        }catch(Exception e){
        	e.printStackTrace();
        } 
        finally {
            response.close();
            httpClient.close();
        }
        // 得到的是JSON类型的数据需要第三方解析JSON的jar包来解析
        return result;
    }
	
    /**
     * @author JuoChiu
     * 此方法是把传进的字节流转化为相应的字符串并返回，此方法一般在网络请求中用到
     * @param is
     * @param charset:编码(UTF-8)
     * @return
     * @throws Exception
     */
    public static String ConvertStreamToString(InputStream is, String charset)
            throws Exception {
        StringBuilder sb = new StringBuilder();
        try (InputStreamReader inputStreamReader = new InputStreamReader(is,charset)) {
            try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\r\n");
                }
            }
        }
        return sb.toString();
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) throws IOException {
        String urlNameString = url+"?"+param;
        String result="";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            HttpGet httpGet = new HttpGet(urlNameString);
            // 执行网络请求
            response = httpClient.execute(httpGet);
            // 获取请求实体
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                // ConverStreamToString是下面写的一个方法是把网络请求的字节流转换为utf8的字符串
                result = ConvertStreamToString(resEntity.getContent(), "UTF-8");
            }
            EntityUtils.consume(resEntity);
        } catch (Exception e) {
        } finally {
            // 关闭请求
            response.close();
            httpClient.close();
        }
        return result;
    }

}
